package com.retailcloud.inventoryservice.service.impl;

import com.retailcloud.commonutils.constant.UserRedisKeyConstant;
import com.retailcloud.commonutils.dto.UserDTO;
import com.retailcloud.commonutils.utils.HttpContextUtils;
import com.retailcloud.commonutils.utils.RedisUtils;
import com.retailcloud.inventoryservice.entity.ProductInfoEntity;
import com.sitech.idworkstarter.IdWorkService;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retailcloud.commonutils.utils.PageUtils;
import com.retailcloud.commonutils.utils.Query;

import com.retailcloud.inventoryservice.dao.ProductCategoryDao;
import com.retailcloud.inventoryservice.entity.ProductCategoryEntity;
import com.retailcloud.inventoryservice.service.ProductCategoryService;
import com.retailcloud.inventoryservice.service.ProductInfoService;

import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
import java.util.Arrays;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("productCategoryService")
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryDao, ProductCategoryEntity>
        implements ProductCategoryService {

    @Resource
    RedisUtils redisUtils;
    @Resource
    IdWorkService idWorkService;
    @Resource
    private ProductInfoService productInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String userName = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        if (StringUtils.isEmpty(userName)) {
            throw new IllegalArgumentException("用户信息不能为空");
        }

        // 从缓存中获取用户信息
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + userName, UserDTO.class);
        if (userDTO == null) {
            throw new IllegalStateException("未找到用户信息，请重新登录");
        }

        // 构建查询条件
        QueryWrapper<ProductCategoryEntity> queryWrapper = new QueryWrapper<>();
        // 添加租户过滤条件
        queryWrapper.eq("tenant_id", userDTO.getTenantId());

        // 如果传入了名称参数，添加名称模糊查询
        String categoryName = (String) params.get("name");
        if (StringUtils.isNotEmpty(categoryName)) {
            queryWrapper.like("name", categoryName);
        }

        // 添加创建时间降序排序
        queryWrapper.orderByDesc("created_at");

        IPage<ProductCategoryEntity> page = this.page(
                new Query<ProductCategoryEntity>().getPage(params),
                queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public void saveCategory(ProductCategoryEntity productCategory) {
        // 验证请求对象是否为空
        if (productCategory == null) {
            throw new IllegalArgumentException("产品类别信息不能为空");
        }

        // 验证必要字段
        if (StringUtils.isEmpty(productCategory.getName())) {
            throw new IllegalArgumentException("类别名称不能为空");
        }

        String userName = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        if (StringUtils.isEmpty(userName)) {
            throw new IllegalArgumentException("用户信息不能为空");
        }

        // 从缓存中获取用户信息
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + userName, UserDTO.class);
        if (userDTO == null) {
            throw new IllegalStateException("未找到用户信息，请重新登录");
        }

        try {
            productCategory.setCreatedBy(userDTO.getWechatOpenid());
            productCategory.setUpdatedBy(userDTO.getWechatOpenid());
            productCategory.setId(idWorkService.getSEQByKey("id_seq"));
            productCategory.setTenantId(userDTO.getTenantId());
            productCategory.setCreatedAt(new Date());
            productCategory.setUpdatedAt(new Date());
            baseMapper.insert(productCategory);
        } catch (Exception e) {
            log.error("保存产品类别失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存产品类别失败", e);
        }
    }

    @Override
    public ProductCategoryEntity getCategoryById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }

        String userName = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        if (StringUtils.isEmpty(userName)) {
            throw new IllegalArgumentException("用户信息不能为空");
        }

        // 从缓存中获取用户信息
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + userName, UserDTO.class);
        if (userDTO == null) {
            throw new IllegalStateException("未找到用户信息，请重新登录");
        }

        // 构建查询条件，确保只能查询到自己租户的数据
        QueryWrapper<ProductCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id)
                .eq("tenant_id", userDTO.getTenantId());

        ProductCategoryEntity category = baseMapper.selectOne(queryWrapper);
        if (category == null) {
            throw new IllegalStateException("未找到该分类信息");
        }

        return category;
    }

    @Override
    public void updateCategory(ProductCategoryEntity productCategory) {

        String userName = HttpContextUtils.getHttpServletRequest().getHeader("X-User-Name");
        UserDTO userDTO = redisUtils.get(UserRedisKeyConstant.USER_TOKEN_USER_KEY + userName, UserDTO.class);

        // 设置更新时间和更新人
        productCategory.setUpdatedAt(new Date());
        productCategory.setUpdatedBy(userDTO.getWechatOpenid());

        baseMapper.updateById(productCategory);
    }

    @Override
    public void deleteCategories(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new IllegalArgumentException("删除的ID不能为空");
        }

        // 验证所有要删除的分类是否属于当前租户，并检查是否有关联商品
        for (Long id : ids) {
            // 验证分类归属
           // getCategoryById(id);

            // 检查分类下是否有商品
            QueryWrapper<ProductInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_id", id);
            int count = productInfoService.count(queryWrapper);

            if (count > 0) {
                ProductCategoryEntity category = getById(id);
                throw new IllegalStateException("分类【" + category.getName() + "】下有" + count + "个商品，不能删除");
            }
        }

        // 所有检查通过后，执行删除
        removeByIds(Arrays.asList(ids));
    }

}
